<?php

namespace App\Http\Controllers\Home\Orders\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Redis;

class OrdersApi extends Controller
{

	/**
	 * 订单确认页面方法,查询加入订单的商品以及用户收货地址
	 * @param $request
	 * @return \Illuminate\Http\RedirectResponse
	 */
	public function confirmOrders($request)
	{
		//判断用户是否登录,登录了就执行订单添加,没有就跳转到登录页面
		if (Session::has('home_user')) {
			$sum = 0;
			//获取订单商品信息
			foreach ($request->pid as $item) {
				$dataInfo = DB::table('goods_price as gp')
					->select(['g.gname','g.is_member_price','g.score','g.pic','gp.id','gp.gid','gp.price', 'gp.discount_price', 'gp.storage', 'gp.size', 'gp.color','gp.state as gpstate'])
					->leftJoin('goods as g','g.id','=','gp.gid')
					->where('gp.id','=',"$item")
					->get()->toArray();
				$num = "num_".$item;
				$dataInfo[0]->buynum = $request->$num;
				$dataInfo[0]->dealprice = $request->$num * $dataInfo[0]->discount_price;
				$sum += $dataInfo[0]->dealprice;
				$data['sum'] = $sum;
				$data[] = $dataInfo;
			}
			//获取用户id及其收货地址
			$uid = Session::get('home_user')['id'];
			$data['address'] = DB::table('address')->where('uid','=',"$uid")->get()->toArray();
			//查询用户积分
			$userscore = DB::table('home_users')->select('user_score')->find("$uid");
			$data['score'] = $userscore->user_score;
			return $data;
		}else {
			return false;
		}
	}


	public function dealOrders($request)
	{
		//判断用户是否登录,登录了就执行订单添加,没有就跳转到登录页面
		if (Session::has('home_user')) {
			DB::beginTransaction();
			//获取用户id信息
			$uid = Session::get('home_user')['id'];

			//查询收货地址信息,并存入data数组
			$aid = $request->aid;
			$addInfo = DB::table('address')
				->select('address','phone','link_man','code','state')
				->where('id','=',"$aid")
				->get()->toArray();
			foreach ($addInfo as $addr) {
				$data['address'] = $addr->address;
				$data['phone'] = $addr->phone;
				$data['link_man'] = $addr->link_man;
				$data['code'] = $addr->code;
			}
			// dd($addInfo);
//			$data['mess']= $request->message;
			$data['aid'] = $aid;
			$data['uid'] = $uid;
//			$data['uid'] = 1;
			//准备并存入订单号
			$ordersNum = 'B2C'.date('YmdHis',time()).mt_rand(100,999);
			$data['orders_num'] = $ordersNum;
			//存入订单状态
			$data['state'] = 0;
			$data['created_at'] = date('Y-m-d H:i:s',time());
			$data['updated_at'] = date('Y-m-d H:i:s',time());
//			dd($request);
			$ordersSum = '';
			for ($i=0; $i<count($request->gname); $i++){
				$ordersSum += $request->buynum[$i] * $request->price[$i];
			}
			$data['orders_sum'] = $ordersSum;
			//判断用户是否使用积分
			if ( isset($request->userscore) ) {
				$oldscore = DB::table('home_users')->select('user_score')->find($uid);
				$uScore = $oldscore->user_score - $request->userscore;
				$updRes = DB::table('home_users')->where('id','=',"$uid")->update(['user_score'=>$uScore]);
				//查询积分能够抵扣的RMB
				$discount = DB::table('score')->get()->toArray();
				$data['orders_sum'] = $data['orders_sum'] - $data['orders_sum'] * $discount[0]->relation;
			}
//			dd($data);
			//插入订单表,并获取id
			$insertId = DB::table('orders')->insertGetId($data);
			//准备订单详情的数据
			$dealprice = 1;//商品成交价格:实际价格-折扣-积分抵扣
			for ($i=0; $i<count($request->gname); $i++){
			    $info[$i]['gname'] = $request->gname[$i];
			    $info[$i]['gprice_id'] = $request->id[$i];
			    $info[$i]['deal_price'] = $request->price[$i];
			    $info[$i]['size'] = $request->size[$i];
			    $info[$i]['color'] = $request->color[$i];
			    $info[$i]['buy_num'] = $request->buynum[$i];
			    $info[$i]['oid']=$insertId;
			    $info[$i]['created_at']=date('Y-m-d H:i:s',time());
			    $info[$i]['updated_at']=date('Y-m-d H:i:s',time());
//			    dd($info);
				//插入订单详情表,并获取id
				$addId = DB::table('orders_details')->insertGetId($info[$i]);
				if ( $addId ) {
					$addToDetails[] = $addId;

					//删除购物车里面的对应商品
					$gid = $request->gid[$i];
					$pid = $request->id[$i];
					$res = Redis::hdel("userCart:{$uid}","userCart:{$gid}:{$pid}");

					//减少数据库对应商品库存
					$storage = DB::table('goods_price')->select('storage')->find("$pid");
					$stock = $storage->storage - $request->buynum[$i];
					$updateRes = DB::table('goods_price')->where('id','=',"$pid")->update(['storage'=>$stock]);

					//增加商品的销售量
					$sales = DB::table('goods_price')->select('sales')->find("$pid");
					$sal = $sales->sales + $request->buynum[$i];
					$updateResult = DB::table('goods_price')->where('id','=',"$pid")->update(['sales'=>$sal]);


					//判断鞋子是否加积分,加的话就加上
					if ( $request->score > 0 ) {
					    $score = DB::table('home_users')->select('user_score')->find($uid);
					    $userScore = $score->user_score + $request->score;
						$newRes = DB::table('home_users')->where('id','=',"$uid")->update(['user_score'=>$userScore]);
					}

				} else {
					//由于未知原因购买失败,则返回0
					$addToDetails[] = 0;
				}

			}

			if ($stock > -1 && $updateRes ) {
				DB::commit();
				$ordersData = DB::table('orders')->find($insertId);
//				$ordersData->pic = $request->pic;
				return $ordersData;
			} else {
				DB::rollBack();
				return false;
			}
		}else {
			return false;
		}
    }

	public function dopay($oid)
	{
		$res = DB::table('orders')->where('id','=',"$oid")->update(['state'=>1]);
		if ( $res ) {
		    return true;
		} else {
			return false;
		}
    }

	public function dobuy($gid, $pid, $num)
	{
		if (Session::has('home_user')) {
			$sum = '';
			$dataInfo = DB::table('goods_price as gp')
				->select(['g.gname', 'g.is_member_price', 'g.score', 'g.pic', 'gp.id', 'gp.gid', 'gp.price', 'gp.discount_price', 'gp.storage', 'gp.size', 'gp.color', 'gp.state as gpstate'])
				->leftJoin('goods as g', 'g.id', '=', 'gp.gid')
				->where('gp.id', '=', "$pid")
				->get()->toArray();
			$dataInfo[0]->buynum = $num;
			$dataInfo[0]->dealprice = $num * $dataInfo[0]->price;
			$sum += $dataInfo[0]->dealprice;
			$data['sum'] = $sum;
			$data[] = $dataInfo;
			//获取用户id及其收货地址
			$uid = Session::get('home_user')['id'];
			$data['address'] = DB::table('address')->where('uid', '=', "$uid")->get()->toArray();
			//查询用户积分
			$userscore = DB::table('home_users')->select('user_score')->find("$uid");
			$data['score'] = $userscore->user_score;
			return $data;
		}else {
			return false;
		}
    }
}
